<template>
    <el-form style="margin: 20px;max-width: 400px" :model="form" ref="formRef" :rules="rules" label-width="100px">
        <el-form-item prop="oldpassword" label="旧密码">
            <el-input v-model="form.oldpassword" placeholder="请输入旧密码" clearable />
        </el-form-item>
        <el-form-item prop="newpassword" label="新密码">
            <el-input v-model="form.newpassword" placeholder="请输入新密码" clearable />
        </el-form-item>
        <el-form-item prop="respassword" label="确认密码">
            <el-input v-model="form.respassword" placeholder="请确认新密码" clearable />
        </el-form-item>
        <el-form-item class="btn">
            <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
            <el-button type="primary" @click="resetForm(formRef)">取消</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { updatePassword } from '@/api/user';
import { useRouter } from "vue-router";
const router = useRouter();

const rules = reactive({
    oldpassword: { required: true, message: '请输入旧密码', trigger: 'blur' },
    newpassword: { required: true, message: '请输入新密码', trigger: 'blur' },
    respassword: { required: true, message: '请确认新密码', trigger: 'blur' },
})

const form = reactive({
    oldpassword: '',
    newpassword: '',
    respassword: ''
})

const formRef = ref(null);

const updatePwd = async () => {
    const data = {
        newpassword: form.newpassword,
        oldpassword: form.oldpassword,
        role: JSON.parse(sessionStorage.getItem('role'))
    }
    const res = await updatePassword(data)
    if (res.code === 0) {
        ElMessage.success(res.data);
        router.push("/login");
        resetForm(formRef);
    } else {
        ElMessage.error(res.msg);
    }
}

const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid && form.newpassword == form.respassword) {
            console.log('submit!')
            updatePwd()
        } else if (valid) {
            ElMessage.warning("两次新密码不一致");
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

</script>

<style lang="scss" scoped>
.btn {
    :deep(.el-form-item__content) {
        justify-content: center !important;
    }
}
</style>